package com.elephant.leil.generator.utils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUtils {


    /**
     * 压缩目录
     *
     * @param zipOutPath  压缩文件输出路径
     * @param zipFileName 压缩文件名称
     * @param targetDir   目标压缩文件夹
     * @throws IOException
     */
    public static void zipDir(String zipOutPath, String zipFileName, String targetDir) throws IOException {
        File targetZipDir = new File(targetDir);
        if (!targetZipDir.isDirectory()) {
            throw new IOException("目标压缩路径不是目录");
        }
        // 判断压缩文件保存的路径是否为源文件路径的子文件夹，如果是，则抛出异常（防止无限递归压缩的发生）
        if (targetZipDir.isDirectory() && zipOutPath.indexOf(targetDir) != -1) {
            throw new IOException("压缩文件输出路径不能为目标压缩目录的子路径");
        }
        File zipFile = new File(zipOutPath + File.separator + zipFileName);
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
        addEntry(targetZipDir, zos, "");
        zos.closeEntry();
        zos.close();
    }

    private static void addEntry(File file, ZipOutputStream zos, String root) throws IOException {
        for (File f : file.listFiles()) {
            if (f.isDirectory()) {
                addEntry(f, zos, root + File.separator + f.getName());
            } else {
                ZipEntry zipEntry = new ZipEntry(root + File.separator + f.getName());
                zos.putNextEntry(zipEntry);
                FileInputStream fis = new FileInputStream(f);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, len);
                }
                fis.close();
            }
        }
    }


    /**
     * 解压zip文件
     * @param zipFilePath       zip文件路径
     * @param destDir           解压目标路径
     * @throws IOException
     */
    public static void unZip(String zipFilePath, String destDir) throws IOException {
        FileInputStream fis = new FileInputStream(zipFilePath);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            File outFile = new File(destDir + File.separator + entry.getName());
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = zis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }
        zis.closeEntry();
        zis.close();
        fis.close();
    }


}
